package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @Description
 * @date 2022/5/16 9:34
 **/
public class HttpServletRequest {
    private Socket socket;
    private String method;
    private String uri;
    private String protoclo;
    private Map<String, String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;

       parseRequestLine();

       parseHeaders();

       parseContent();

    }
    /**
     * @author
     * @description //TODO
     * @date 2022/5/16 10:25
 * @return java.lang.String
     */
    private void parseRequestLine() throws IOException {
        String line = readline();
        String[] strings = line.split(" ");

        method = strings[0];
        uri = strings[1];
        protoclo = strings[2];
    }
    private void parseHeaders() throws IOException {
        //解析消息头
        String line ;

        while (!(line = readline()).isEmpty()) {
            System.out.println(line);
            String[] split = line.split(": ");
            headers.put(split[0], split[1]);
        }
//        System.out.println(headers);

    }
    private void parseContent(){

    }



    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtoclo() {
        return protoclo;
    }

    public String getHeader(String name){
        return headers.get(name);
    }

    private String readline() throws IOException {

        InputStream inputStream = socket.getInputStream();
        StringBuilder sb = new StringBuilder();
        int d;
        char cur = 'a';
        char pre = 'a';
        while ((d = inputStream.read()) != -1) {
            cur = (char) d;
            if (pre == 13 && cur == 10) {
                break;
            }
            sb.append(cur);
            pre = cur;
        }
        String line = sb.toString().trim();
        return line;

    }


}
